/************************************************************************************
**  
* @copyright (c) 2013-2100,  Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file	    duye_inotify.cpp
* @version     
* @brief      
* @author
* @date	    2013-03-30
* @note 
*
*  1. 2018-03-30 Created this file
* 
*/
#include <errno.h>
#include <sys/stat.h>
#include <duye_logger.h>
#include <duye_inotify.h>

namespace duye {

static const int8* DUYE_LOG_PREFIX = "duye.system.inotify";

Inotify::Inotify() : m_fd(-1) {}

Inotify::~Inotify() {
	if (m_fd > 0) {
		close(m_fd);
	}
}

int32 Inotify::init() {
	m_fd = inotify_init();
	if (m_fd == -1) {
		DUYE_ERROR("inotify_init() == -1");
	}

	return m_fd;
}

int32 Inotify::addWatch(const int8* path, const uint32 mask) {
	if (m_fd <= 0) {
		DUYE_ERROR("fd is %d", m_fd);
		return false;
	}

	struct stat	st;
	if (lstat(path, &st) < 0) {
		DUYE_ERROR("lstat %s error: %s", path, strerror(errno));
		return false;
	}

	return inotify_add_watch(m_fd, path, mask);
}

bool Inotify::delWatch(const int32 wd) {
	if (m_fd <= 0) {
		DUYE_ERROR("fd is %d", m_fd);
		return false;
	}

	return inotify_rm_watch (m_fd, wd) == 0 ? true : false;
}

}
